// 草图 - 阵列
import {
  BaseCommand,
  cadAppLog,
  CommandDialog,
  CommandDialogPlacement,
  EventsRes,
  ICurve,
  KEYBOARD_KEY,
  ObjInfo,
  ParameterObjectType,
} from '@amcax/base';
import { ctx2 } from '@app-cad/module';
import i18n from '@app-cad/common/utils/i18next';
import { useEffect, useState } from 'react';
import {
  SKETCH_CENTEREVENTS,
  sketchEventCenter,
} from '../../../events/SketchEventCenter';
import { Vector2 } from 'three-legacy';
import { wsApi } from '@app-cad/server';
import {
  basicSketchIds,
  renderSketch,
  sketchPreview,
} from '@app-cad/common/utils';
import { CommandFormWrapper } from '@app-cad/common/components/command-form';
import { PickInputForFocus2D } from '@app-cad/common/components/command-form/auto-focus/pick-input';
import { InputWithFormat } from '@app-base/common/components/command-form/InputWithFormat';
import { Checkbox } from 'antd';
import { CommandFormFooter } from '@app-base/common/components/command-form/footer';
interface ArrayDialogProps {
  title: string;
  placement: CommandDialogPlacement;
  props: ObjInfo;
  onClose: () => void;
}
function CircleArrayCommand({ onClose, title }: ArrayDialogProps) {
  const sketchId = sketchEventCenter().getSketchInfo().sketchId;
  const [count, setCount] = useState(2);
  const [angle, setAngle] = useState<string | number>(360);
  const [reverse, setReverse] = useState(false);
  useEffect(() => {
    sketchEventCenter()
      .setState('array')
      .on(SKETCH_CENTEREVENTS.KEYUP, onKeyUp);
    return () => {
      sketchEventCenter().setDefault().off(SKETCH_CENTEREVENTS.KEYUP, onKeyUp);
      ctx2.cadScene.assisGroup.clear();
    };
  }, []);
  const onKeyUp = (e: EventsRes<KeyboardEvent>) => {
    if (e.key === KEYBOARD_KEY.ESC) {
      onClose();
    }
  };
  const [patternValue, setPatternValue] = useState([]);
  const [directionValue, setDirectionValue] = useState([]);
  const [directionData, setDirectionData] = useState([]);
  const onPatternData = (ids: string[]) => {
    setPatternValue(ids);
  };
  useEffect(() => {
    if (patternValue.length > 0 && directionValue.length > 0) {
      ctx2.cadScene.assisGroup.clear();
      preview();
    } else {
      ctx2.cadScene.assisGroup.clear();
    }
  }, [patternValue, directionValue, count, angle, reverse]);
  const preview = async () => {
    const centerPoint: Vector2 = new Vector2(
      directionData[0][0],
      directionData[0][1],
    );
    cadAppLog('centerPoint', centerPoint);
    const excludeValue = basicSketchIds;
    const patternValues = patternValue.filter((item) => {
      return !excludeValue.includes(item);
    });
    const res = await wsApi.arraySketchCurve(
      sketchId,
      patternValues,
      count,
      null,
      null,
      centerPoint,
      angle,
      true,
      reverse,
    );
    sketchPreview(res.curves);
  };

  const onDirectionData = (ids: string[], picked: ICurve[]) => {
    if (picked.length === 0) {
      setDirectionValue([]);
    } else if (picked && picked[0].type === 'Point') {
      cadAppLog('Picker2D', picked[0].vertices);
      ctx2.cadScene.assisGroup.clear();
      setDirectionValue(ids);
      setDirectionData(picked[0].vertices);
    }
  };
  const onSubmit = async () => {
    if (directionData && directionData.length > 0) {
      const centerPoint: Vector2 = new Vector2(
        directionData[0][0],
        directionData[0][1],
      );
      cadAppLog('centerPoint', centerPoint);
      const excludeValue = basicSketchIds;
      const patternValues = patternValue.filter((item) => {
        return !excludeValue.includes(item);
      });
      const res = await wsApi.arraySketchCurve(
        sketchId,
        patternValues,
        count,
        null,
        null,
        centerPoint,
        angle,
        false,
        reverse,
      );

      onClose();
      await renderSketch(sketchId, res);
      ctx2.cadScene.assisGroup.clear();
    }
  };
  return (
    <CommandDialog
      title={title}
      placement='topLeft'
      className='sketchDialog'
      onClose={onClose}
    >
      <CommandFormWrapper>
        <PickInputForFocus2D
          value={patternValue}
          onPick={onPatternData}
          controlled
          isMulti
          autoFocus
          placeholder='阵列实体'
        />
        <PickInputForFocus2D
          value={directionValue}
          onPick={onDirectionData}
          controlled
          placeholder='阵列方向'
        />
        <div className='flex w-full items-center text-sm'>
          数量：
          <InputWithFormat
            className='flex-1'
            value={count}
            min={2}
            onChange={(val) => setCount(val as number)}
            disableParameter
            inputType={ParameterObjectType.Integer}
          />
        </div>
        <div className='flex w-full items-center text-sm'>
          角度：
          <InputWithFormat
            className='flex-1'
            value={angle}
            min={1}
            max={360}
            onChange={setAngle}
            inputType={ParameterObjectType.Angle}
          />
        </div>
        <Checkbox
          checked={reverse}
          onChange={(e) => setReverse(e.target.checked)}
        >
          反向
        </Checkbox>
        <CommandFormFooter
          onSubmit={onSubmit}
          showCancel={false}
          submitText='执行'
        />
      </CommandFormWrapper>
    </CommandDialog>
  );
}

export const cmdCircleArray: BaseCommand = {
  id: 'cmdCircleArray',
  label: 'command.array-circle',
  icon: 'commands/sketch/sketch-circle-array',
  group: 'sketch',
  create: (label: string, onClose: () => void, props) => (
    <CircleArrayCommand
      title={i18n.t(label)}
      onClose={onClose}
      props={props}
      placement='topLeft'
    />
  ),
};
